package cn.agiledata.bank.common.util;

import java.lang.reflect.Method;
import java.text.DecimalFormat;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.vnv.infrastructure.exception.ErrorCode;
import com.vnv.infrastructure.exception.IPBException;
import com.vnv.vol.common.Constants;


/**
 * Utility class to convert one object to another.
 * 
 * <p>
 * <a href="ConvertUtil.java.html"><i>View Source</i></a>
 * </p>
 * 
 */
public final class ConvertUtil {

    //~ Static fields/initializers =============================================

    private static Log log = LogFactory.getLog(ConvertUtil.class);


    /**
     * This method inspects a POJO or Form and figures out its pojo/form
     * equivalent.
     *
     * @param o the object to inspect
     * @return the Class of the persistable object
     * @throws ClassNotFoundException
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static Object getOpposingObject(Object o) throws ClassNotFoundException,
                                                InstantiationException,
                                                IllegalAccessException {
        String name = o.getClass().getName();
        name = name.substring(0, name.lastIndexOf("Form"));
        Class obj = Class.forName(name);
        return obj.newInstance();
    }

    /**
     * Convenience method to convert a form to a POJO and back again
     *
     * @param o the object to tranfer properties from
     * @return converted object
     */
    public static Object convert(Object o) throws Exception {
        if (o == null) {
        	return null;
        }
        Object target = getOpposingObject(o);
        BeanUtils.copyProperties(target,o);
        return target;
    }
    /**
     * author joe
     * date   2006-03-16
     * properse :get the directly address.if the 
     * 		SYS_PARAM_IPEDO_CONF_PATH result is null then 
     * 		gave it a default.this is only used by test. 
     * @return
     */
    public static String getDirStr(){
        String SYS_PARAM_IPEDO_CONF_PATH = 
    		Constants.IPEDO_CONF_PATH;
    	if (SYS_PARAM_IPEDO_CONF_PATH == null){
    		SYS_PARAM_IPEDO_CONF_PATH = 
    			System.getProperty("user.dir")+"\\web\\WEB-INF\\conf\\spring\\";
    	}else{
    		SYS_PARAM_IPEDO_CONF_PATH+="spring\\";
    	}
    	return SYS_PARAM_IPEDO_CONF_PATH;
    }
    /**
     * Utilize Reflection API to invoke method. Useful for backward compatibility.
     *
     * @param instance      instance object
     * @param methodName    method name
     * @param argTypes      argument types
     * @param args          arguments
     * @return object
     * @throws IPBException
     */
    private static Object invokeMethodByFiled(Object instance, String methodName,
                                        Class[] argTypes, Object[] args) throws IPBException {
        try {
            Method method = instance.getClass().getMethod(methodName, argTypes);
            return method.invoke(instance, args);
        }
        catch (Exception e) {
            log.error(e.getMessage(), e);
            String[] params = {methodName, instance.getClass().getName()};
            throw new IPBException(ErrorCode.INVOKE_METHOD_ERROR, params, e);
        }
    }
    
    
    /**
     * Utilize Reflection API to invoke method. Useful for backward compatibility.
     *
     * @param instance      instance object
     * @param methodName    method name
     * @param argTypes      argument types
     * @param args          arguments
     * @return object
     * @throws IPBException
     */
    public static Object invokeGetMethod(Object instance, String methodName
                                       ) throws IPBException {
        try {
        	Method []m = instance.getClass().getMethods();
            Method method = instance.getClass().getMethod(methodName, null);
            return method.invoke(instance,new Object[]{});
        }
        catch (Exception e) {
            log.error(e.getMessage(), e);
            String[] params = {methodName, instance.getClass().getName()};
            throw new IPBException(ErrorCode.INVOKE_METHOD_ERROR, params, e);
        }
    }
    
    public static String getRequestURL (HttpServletRequest request) {
    	StringBuffer url = new StringBuffer () ;
    	url.append(Constant.WEBROOT_URL);
    	url.append(request.getContextPath()) ;
    	
    	return url.toString() ;
    } 
    
	public static String parseDec(Object dec, String parseStyle) {
		String newObj = "";
		try {
			DecimalFormat df = new DecimalFormat(parseStyle);
			newObj = df.format(dec);

		} catch (IllegalArgumentException ex) {

		} finally {
			return newObj;
		}
	}  
	
	public static String toUTF(String inPara)
	 {
	    char temChr;
	    int ascChr;
	    int i;
	    String rtStr=new String("");
	    if(inPara==null)
	    { 
	      inPara="";
	    } 
	    for(i=0;i<inPara.length();i++)
	    {
	      temChr=inPara.charAt(i);
	      ascChr=temChr+0;
	      rtStr=rtStr+"&#x"+Integer.toHexString(ascChr)+";";
	    }
	    return rtStr;
	  }
	
	
	/**
	 * ���Сд���õ���д�������
	 * @param lowerMoney
	 * @return
	 */
	public static String getUpperMoney(String lowerMoney) {
	    char[] hunit={'拾','佰','仟'};                                               //段内位置表示
	    char[] vunit={'万','亿'};                                                     //段名表示
	    char[] digit={'零','壹','贰','叁','肆','伍','陆','柒','捌','玖'};  //数字表示
	    long midVal = (long)(Double.parseDouble(lowerMoney)*100);                                      //转化成整形
	    String valStr=String.valueOf(midVal);                                //转化成字符串
	    if("0".equals(valStr)) {
	    	return "零元整";
	    }
	    String head=valStr.substring(0,valStr.length()-2);               //取整数部分
	    String rail=valStr.substring(valStr.length()-2);                     //取小数部分

	    String prefix="";                                                                 //整数部分转化的结果
	    String suffix="";                                                                  //小数部分转化的结果
	    //处理小数点后面的数
	    if(rail.equals("00")){                                                            //如果小数部分为0
	      suffix="整";
	    } else{
	      suffix=digit[rail.charAt(0)-'0']+"角"+digit[rail.charAt(1)-'0']+"分";        //否则把角分转化出来
	    }
	    //处理小数点前面的数
	    char[] chDig=head.toCharArray();                                                         //把整数部分转化成字符数组
	    char zero='0';                                                                                          //标志'0'表示出现过0
	    byte zeroSerNum = 0;                                                                            //连续出现0的次数
	    for(int i=0;i<chDig.length;i++){                                                               //循环处理每个数字
	      int idx=(chDig.length-i-1)%4;                                                                //取段内位置
	      int vidx=(chDig.length-i-1)/4;                                                                //取段位置
	      if(chDig[i]=='0'){                                                                                  //如果当前字符是0
	        zeroSerNum++;                                                                                 //连续0次数递增
	        if(zero == '0'){                                                                                    //标志
	          zero=digit[0];
	        } else if(idx==0 && vidx >0 &&zeroSerNum < 4){
	          prefix += vunit[vidx-1];
	          zero='0';
	        }
	        continue;
	      }
	      zeroSerNum = 0;                                                                                    //连续0次数清零
	      if(zero != '0') {                                                                                        //如果标志不为0,则加上,例如万,亿什么的
	        prefix+=zero;
	        zero='0';
	      }
	      prefix+=digit[chDig[i]-'0'];                                                                        //转化该数字表示
	      if(idx > 0) prefix += hunit[idx-1];                  
	      if(idx==0 && vidx>0){
	        prefix+=vunit[vidx-1];                                                                             //段结束位置应该加上段名如万,亿
	      }
	    }

	    if(prefix.length() > 0) prefix += '元';                                                             //如果整数部分存在,则有圆的字样
	    return prefix+suffix;                                                                                     //返回正确表示
	}
	/**
	 * 
	 * @param b
	 * @return
	 */
	public static String convertFromBooleanToString(boolean b) {
		if(b) {
			return "Y";
		} else {
			return "N";
		}
	}
	
}
